package com.yosaa.back.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yosaa.back.entity.FitnessRecord;
import com.yosaa.back.entity.UserInfo;
import com.yosaa.back.service.IFitnessProjectService;
import com.yosaa.back.service.IFitnessRecordService;
import com.yosaa.back.service.IUsersService;
import com.yosaa.back.utils.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 体测成绩记录表，记录每次体测的具体结果 前端控制器
 * </p>
 *

 */
@RestController
@RequestMapping("/fitness-record")
public class FitnessRecordController {

    @Autowired
    private IFitnessRecordService fitnessRecordService;
    @Autowired
    private IUsersService  usersService;
    @Autowired
    private IFitnessProjectService fitnessProjectService  ;

    @GetMapping("/list")
    public ResponseEntity getFitnessRecordList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String username, // 改为 String 支持模糊查询
            @RequestParam(required = false) String projectName, // 改为 String 支持模糊查询
            @RequestParam(required = false) String testDate) {


        // 分页对象
        Page<FitnessRecord> recordPage = new Page<>(page, size);

        // 查询条件
        QueryWrapper<FitnessRecord> queryWrapper = new QueryWrapper<>();
        if (testDate != null && !testDate.trim().isEmpty()) {
            queryWrapper.eq("test_date", testDate);
        }

        Integer userId = StpUtil.getLoginIdAsInt();
        UserInfo userInfo = usersService.getById(userId);
        if (!userInfo.getRole().equals("admin")) {
            queryWrapper.eq("user_id", userId);
            // 没有模糊查询条件时直接查询分页数据
            IPage<FitnessRecord> result = fitnessRecordService.page(recordPage, queryWrapper);

            // 设置用户名和项目名
            result.getRecords().forEach(record -> {
                record.setProjectName(fitnessProjectService.getById(record.getProjectId()).getProjectName());
                record.setUserName(usersService.getById(record.getUserId()).getUsername());
            });

        }

        // 处理用户名和项目名模糊查询逻辑
        if ((username != null && !username.trim().isEmpty()) ||
                (projectName != null && !projectName.trim().isEmpty())) {

            // 获取所有记录
            List<FitnessRecord> allRecords = fitnessRecordService.list(queryWrapper);

            // 根据模糊查询条件过滤记录
            List<FitnessRecord> filteredRecords = allRecords.stream()
                    .filter(record -> {
                        // 从关联表获取 username 和 projectName
                        String actualUsername = usersService.getById(record.getUserId()).getUsername();
                        String actualProjectName = fitnessProjectService.getById(record.getProjectId()).getProjectName();

                        // 检查条件是否匹配
                        boolean usernameMatches = username == null || actualUsername.contains(username);
                        boolean projectNameMatches = projectName == null || actualProjectName.contains(projectName);
                        return usernameMatches && projectNameMatches;
                    })
                    .collect(Collectors.toList());

            // 手动分页
            int start = (page - 1) * size;
            int end = Math.min(start + size, filteredRecords.size());
            List<FitnessRecord> paginatedRecords = filteredRecords.subList(start, end);

            paginatedRecords.forEach(record -> {
                        record.setProjectName(fitnessProjectService.getById(record.getProjectId()).getProjectName());
                        record.setUserName(usersService.getById(record.getUserId()).getUsername());
                    });
            // 返回结果
            return ResponseEntity.ok(new ApiResponse(0,
                    new Page<FitnessRecord>()
                            .setRecords(paginatedRecords)
                            .setCurrent(page)
                            .setSize(size)
                            .setTotal(filteredRecords.size()),
                    "操作成功"));
        }

        // 没有模糊查询条件时直接查询分页数据
        IPage<FitnessRecord> result = fitnessRecordService.page(recordPage, queryWrapper);

        // 设置用户名和项目名
        result.getRecords().forEach(record -> {
            record.setProjectName(fitnessProjectService.getById(record.getProjectId()).getProjectName());
            record.setUserName(usersService.getById(record.getUserId()).getUsername());
        });

        return ResponseEntity.ok(new ApiResponse(0, result, "操作成功"));
    }

    @PostMapping("/add")
    public ResponseEntity<ApiResponse> addFitnessRecord(@RequestBody FitnessRecord fitnessRecord) {
        boolean saved = fitnessRecordService.save(fitnessRecord);
        if (saved) {
            return ResponseEntity.ok(new ApiResponse(0, null, "操作成功"));
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(1, null, "操作失败"));
        }
    }

    @PostMapping("/update")
    public ResponseEntity<ApiResponse> updateFitnessRecord(@RequestBody FitnessRecord fitnessRecord) {
        boolean updated = fitnessRecordService.updateById(fitnessRecord);
        if (updated) {
            return ResponseEntity.ok(new ApiResponse(0, null, "操作成功"));
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(1, null, "操作失败"));
        }
    }

    @GetMapping("/get/{id}")
    public ResponseEntity<ApiResponse> getFitnessRecord(@PathVariable Integer id) {
        FitnessRecord fitnessRecord = fitnessRecordService.getById(id);
        if (fitnessRecord != null) {
            return ResponseEntity.ok(new ApiResponse(0, fitnessRecord, "操作成功"));
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(new ApiResponse(1, null, "操作失败"));
        }
    }

    @DeleteMapping("/delete/{id}")
    public ResponseEntity<ApiResponse> deleteFitnessRecord(@PathVariable Integer id) {
        boolean deleted = fitnessRecordService.removeById(id);
        if (deleted) {
            return ResponseEntity.ok(new ApiResponse(0, null, "操作成功"));
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(1, null, "操作失败"));
        }
    }
}